<script>
reader_atom_href = "http://www.google.com/reader/api/0/unread-count?all=true";
var poll_timeout = 60000; // One minute

function update(count) {
  if (typeof(count) == 'number') {
    count = count.toString();
  }
  chrome.browserAction.setBadgeText({ text: count }); 
}

function requestUnreadFeed() {  
  var xhr = new XMLHttpRequest();
  try {
    console.log("request..");
    xhr.onload = function() {
      console.log("readystate: " + xhr.readyState);
      window.clearTimeout(timerId);
      if (xhr.responseXML) {
        /* Ok, we got our feeds */
        console.log("response..");
        var xmlDoc = xhr.responseXML; 
        var fullCountSet = xmlDoc.evaluate("//string", 
            xmlDoc, null, XPathResult.ANY_TYPE, null);
        var fullCountNode = fullCountSet.iterateNext();
        var tempCount = 0;
        while (fullCountNode) {
          if (fullCountNode.textContent.indexOf('reading-list') > -1) {
            tempCount = parseInt(fullCountNode.nextSibling.textContent);
            break;
          }
          fullCountNode = fullCountSet.iterateNext();
        }
        update(tempCount);
      } else {
        /* Must be a login error */
        console.log('Please login: ' + xhr.statusText);
        update('E-LO');
      }

      window.setTimeout(requestUnreadFeed, poll_timeout);
    }
    
    xhr.onerror = function(error) {
      console.log("error: " + error);
    }

    xhr.open("GET", reader_atom_href, true);
    xhr.send(null);

    // Give up after 5 seconds
    var timerId = window.setTimeout(function() {
      console.log("Gave up...");
      update(E-TO);
      xhr.abort();
      /* Try again later... */
      window.setTimeout(requestUnreadFeed, poll_timeout);
    }, 5000);
  } catch(e) {
    console.log("ex: " + e);
    console.error("exception: " + e);
    window.setTimeout(requestUnreadFeed, poll_timeout);
  }
}

requestUnreadFeed();
chrome.browserAction.onClicked.addListener(function(tab) {
  // check if there is a tab opened
  var regEx = /^http:\/\/www\.google\.com\/reader/;
  chrome.tabs.getAllInWindow(null, function(tabs){
    var tabId = null;
    for (var i in tabs) {
      if (regEx.test(tabs[i].url)) {
        console.log('found: ' + [tabs[i].url, tabs[i].id].join(', '));
        tabId = tabs[i].id;
        break;
      }
    }
    if (tabId) {
      chrome.tabs.update(tabId, { selected: true });
    } else {
      chrome.tabs.create({
          url: 'http://www.google.com/reader/'
      });
    }
  });
}); 

</script>
